using System;
using System.Globalization;
using System.Text;

namespace org.synthful.Number
{
    /// <summary>
    /// Offered under Apache Public Licence 2.0
    /// synthful.org
    /// blessedgeek [@] synthful.org
    /// </summary>
    static public class NumericConversions
    {
        static public decimal BinaryToBCD(byte[] bb)
        {
            decimal d = 0; int e10 = 1;
            for (int i = bb.Length - 1; i >= 0; i--)
            {
                int d1 = bb[i] & 0x0f;
                int d2 = bb[i] >> 4;
                d += d1 * e10;
                e10 *= 10;
                d += d2 * e10;
                e10 *= 10;
            }

            return d;
        }


        static public byte[] HexStringToBytes(string s)
        {
            string[] hexChars = s.Split(HexDelim);
            return HexCharsToBytes(hexChars);
        }

        static public byte[] HexCharsToBytes(string[] hexChars)
        {
            byte[] byteVals = new byte[hexChars.Length];
            sbyte b;
            for (int i = 0; i < hexChars.Length; i++)
            {
                b = 0;
                sbyte.TryParse(hexChars[i], NumberStyles.HexNumber, null, out b);
                byteVals[i] = (byte)b;
            }
            return byteVals;
        }

        static public String[] BytesToHexChars(byte[] byteVals)
        {
            String[] hexChar = new String[byteVals.Length];
            for (int i = 0; i < byteVals.Length; i++)
                hexChar[i] = byteVals[i].ToString("X2");


            return hexChar;
        }

        static public String BytesToHexString(byte[] byteVals)
        {
            String hexString = "";
            for (int i = 0; i < byteVals.Length; i++)
                hexString += byteVals[i].ToString("X2") + ' ';

            return hexString;
        }

        static public string HexStringToCharString(string h)
        {
            byte[] bb = HexStringToBytes(h);
            return ByteArrayToString(bb);
        }

        static public string ByteArrayToString(byte[] bb)
        {
            StringBuilder sbuf = new StringBuilder(bb.Length);

            for (int i = 0; i < bb.Length; i++)
            {
                // Convert all null chars to 256 before stuffing into the string
                // because null is a string terminator. Using 256 cheats the string
                // into accepting accepting zero as a non-null char.
                char c = Convert.ToChar(bb[i] == 0 ? 256 : bb[i]);
                sbuf.Append(c);
            }

            return sbuf.ToString();
        }

        static private char[] HexDelim =
            new char[] { ' ', ',', '.', ';', ':', '-', '\t' };
    }
}
